from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyKDE4.plasma import *
from PyKDE4 import plasmascript
from PyKDE4 import kdecore
from PyKDE4 import kdeui
import os
import urllib
PLASMOID_WIDTH=420
PLASMOID_HEIGHT=480
URL='http://dict.youdao.com/m'
URLFULL='http://dict.youdao.com/'
class InputBox(Plasma.LineEdit):
	def __init__(self,parent):
		Plasma.LineEdit.__init__(self, parent.applet)
		self.parent = parent
	def keyPressEvent(self, event):
		if event.key() in [Qt.Key_Return, Qt.Key_Enter]:
			self.parent.lookup()
		else:
			Plasma.LineEdit.keyPressEvent(self, event)

class YoudaoDictApplet(plasmascript.Applet):
	def __init__(self,parent,args=None):
		plasmascript.Applet.__init__(self,parent)
	def lookup(self):
		word = self.inputBox.text().trimmed()
		if word.length() == 0:
			return
		self.inputBox.nativeWidget().selectAll()
		self.web.setUrl(kdecore.KUrl(URL + "/search?q=" + word))
	def openWebBrowser(self):
		query = urllib.quote(self.inputBox.text().trimmed().toUtf8().data())
		if len(query) == 0:
			os.system("xdg-open " + URLFULL)
		else:
			os.system("xdg-open " + URLFULL + "search?q=" + query)
	def init(self):
		self.resize(PLASMOID_WIDTH, PLASMOID_HEIGHT)
		self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
		self.setHasConfigurationInterface(True)

		# the main layout
		self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
		self.setLayout(self.layout)
		# the sub layout of input box and buttons
		inputLayout = QGraphicsLinearLayout(Qt.Horizontal, self.layout)
		# the input box
		self.inputBox = InputBox(self)
		self.inputBox.setClickMessage("input a word and press enter")
		# the buttons
		contentsRoot = kdecore.KGlobal.dirs().locate("data", "plasma/plasmoids/youdao-dict/contents/")
		self.lookupButton = Plasma.PushButton(self.applet)
		self.lookupButton.setImage(contentsRoot + "/images/search.png")
		self.lookupButton.nativeWidget().setToolTip("look up in Youdao dictionary")

		self.openInBrowserButton = Plasma.PushButton(self.applet)
		self.openInBrowserButton.setImage(contentsRoot + "/images/web-browser.png")
		self.openInBrowserButton.nativeWidget().setToolTip("open in web browser")

		# define button behaviors
		self.connect(self.lookupButton, SIGNAL("clicked()"), self.lookup)
		self.connect(self.openInBrowserButton, SIGNAL("clicked()"), self.openWebBrowser)

		inputLayout.addItem(self.inputBox)
		inputLayout.addItem(self.lookupButton)
		inputLayout.addItem(self.openInBrowserButton)
		# A web browser
		self.web = Plasma.WebView()
		self.web.setUrl(kdecore.KUrl("file://" + contentsRoot + "/index.html"))
		# add it to current layout
		self.layout.addItem(inputLayout)
		self.layout.addItem(self.web)
		self.web.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))

def CreateApplet(parent):
	return YoudaoDictApplet(parent)
